#include "Common.hlsl"

#if GPUSkining
#define MAX_BONES	(75)
float4x3 BoneMatrices[MAX_BONES] : register(c8);
#endif

void VSMain(
    float4 InPosition	: POSITION,
#if GPUSkining
	int4 BlendIndices	: BLENDINDICES,
	float4 BlendWeight	: BLENDWEIGHT,
#endif
	half3 InNormal		: NORMAL,
	half3 InTangent		: TANGENT,
	float2 InTexcoord	: TEXCOORD0,
    out float4 Position	: POSITION,
	out half3 Normal	: NORMAL,
	out half3 Tangent	: TANGENT,
	out float2 Texcoord	: TEXCOORD0,
	out float4 PixelPos	: TEXCOORD1,
	uniform float4x4 WorldMatrix : register(c0),
    uniform float4x4 WorldViewProjMatrix : register(c4))
{
#if GPUSkining
	float4x3 BoneMatrix = BlendWeight.x * BoneMatrices[BlendIndices.x];
	BoneMatrix += BlendWeight.y * BoneMatrices[BlendIndices.y];
	BoneMatrix += BlendWeight.z * BoneMatrices[BlendIndices.z];
	BoneMatrix += BlendWeight.w * BoneMatrices[BlendIndices.w];

	InPosition = float4(mul(InPosition, BoneMatrix), 1);
	Normal = mul(Normal, BoneMatrix);
	Tangent = mul(Tangent, BoneMatrix);
#endif
    Position = mul(WorldViewProjMatrix, InPosition);
	Normal = normalize(mul(WorldMatrix, float4(UnPackVector(InNormal), 0)).xyz);
	Tangent = normalize(mul(WorldMatrix, float4(UnPackVector(InTangent), 0)).xyz);
	Texcoord = InTexcoord;
	PixelPos = Position;
}

void PSMain(
	half3 Normal		: NORMAL,
	half3 Tangent		: TANGENT,
	float2 Texcoord		: TEXCOORD0,
	float4 PixelPos		: TEXCOORD1,
    out float4 Color0   : COLOR0,
    out float4 Color1   : COLOR1,
    out float4 Color2   : COLOR2,
    out float4 Color3   : COLOR3)
{
	MaterialParams param = (MaterialParams)0;
	param.Texcoord = Texcoord;

	float3x3 tangentMaxtrix;
	tangentMaxtrix[0] = Tangent;
	tangentMaxtrix[1] = cross(Tangent, Normal);
	tangentMaxtrix[2] = Normal;

    Color0 = float4(GetEmissive(param), 1);
    Color1 = float4(GetDiffuse(param), 1);
    Color2 = float4(mul(tangentMaxtrix, GetNormal(param)), PixelPos.w);
    Color3 = float4(GetSpecular(param), 1);

#if 1
	// do simple lighting for test.
	float3 ambient = float3(0.2, 0.2, 0.2);
	float3 lightDir = -normalize(float3(0.5, -1, 0.1));
	Color0.rgb += ambient + Color1 * dot(lightDir, Normal);
#endif
}
